package com.ruoyi.quartz.task;

import com.ruoyi.cluster.vo.ClusterData;
import com.ruoyi.cluster.vo.ClusterZone;
import com.ruoyi.quartz.util.TaskUtils;
import com.ruoyi.task.domain.KwTaskInfo;
import com.ruoyi.task.service.IKwTaskInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 集群任务
 * 
 * @author gonianer
 */
@Component("clusterTask")
public class ClusterTask
{
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private IKwTaskInfoService taskInfoService;
    @Autowired
    private ClusterTaskHandler clusterTaskHandler;

    @Transactional(rollbackFor = Exception.class)
    public void addCluster(Long clusterId){
        //添加任务步骤
        KwTaskInfo t = TaskUtils.buildTask(clusterId,0L,"addCluster","创建集群",0);
        taskInfoService.insertKwTaskInfo(t);
        //添加子任务
        KwTaskInfo t1 = TaskUtils.buildTask(clusterId,t.getId(),"checkClusterCreate","创建集群预检查",0);
        taskInfoService.insertKwTaskInfo(t1);
        KwTaskInfo t2 = TaskUtils.buildTask(clusterId,t.getId(),"uploadDbResource","上传资源文件",0);
        taskInfoService.insertKwTaskInfo(t2);
        KwTaskInfo t3 = TaskUtils.buildTask(clusterId,t.getId(),"decompressAndCheck","解压并检查资源文件",0);
        taskInfoService.insertKwTaskInfo(t3);
        KwTaskInfo t4 = TaskUtils.buildTask(clusterId,t.getId(),"linkDataDir","建立数据目录连接",0);
        taskInfoService.insertKwTaskInfo(t4);
        KwTaskInfo t5 = TaskUtils.buildTask(clusterId,t.getId(),"startProcess","启动数据库进程",0);
        taskInfoService.insertKwTaskInfo(t5);
        KwTaskInfo t6 = TaskUtils.buildTask(clusterId,t.getId(),"checkProcessStatus","检查数据库进程状态",0);
        taskInfoService.insertKwTaskInfo(t6);
        KwTaskInfo t7 = TaskUtils.buildTask(clusterId,t.getId(),"bootstrapCluster","初始化数据库",0);
        taskInfoService.insertKwTaskInfo(t7);
        KwTaskInfo t8 = TaskUtils.buildTask(clusterId,t.getId(),"waitForClusterOk","等待数据库初始化完成",0);
        taskInfoService.insertKwTaskInfo(t8);
        KwTaskInfo t9 = TaskUtils.buildTask(clusterId,t.getId(),"updateClusterStatus","更新集群状态",0);
        taskInfoService.insertKwTaskInfo(t9);

        //开始执行任务
        clusterTaskHandler.addCluster(t,false);
    }

    @Transactional(rollbackFor = Exception.class)
    public void rollbackCluster(Long taskId){
        if(taskId == null) {
            logger.warn("rollback cluster failed ,taskId is null");
            return;
        }
        //开始执行任务
        clusterTaskHandler.rollbackCluster(taskId);
    }

    @Transactional(rollbackFor = Exception.class)
    public void retryAddCluster(Long taskId){
        if(taskId == null) {
            logger.warn("retry cluster failed ,taskId is null");
            return;
        }
        //开始执行任务
        clusterTaskHandler.retryAddCluster(taskId);
    }

}
